/**
 * @author 雷明浩
 * @date 2025/5/30 14:52
 */
public class Flatten {
    // leetcode 二叉树展开为链表
    // https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/?envType=study-plan-v2&envId=top-100-liked
    public void flatten(TreeNode root) {
        flattenChild(root);
    }

    private TreeNode flattenChild(TreeNode root) {
        if (root == null) {
            return root;
        }
        TreeNode leftTree = flattenChild(root.left);
        TreeNode rightTree = flattenChild(root.right);
        if (leftTree != null) {
            leftTree.left = null;
            TreeNode tmp = root.right;
            root.right = leftTree;
            while (leftTree.right != null) {
                leftTree = leftTree.right;
            }
            leftTree.right = tmp;
            root.left = null;
        }
        return root;
    }
}